package com.hhh.demo.sx.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hhh.demo.sx.bean.Shop;
import com.hhh.demo.sx.bean.User;
import com.hhh.demo.sx.exception.MyException;
import com.hhh.demo.sx.service.ShopService;
import com.hhh.demo.sx.service.UserService;
import com.hhh.demo.sx.util.MD5Util;
import com.hhh.demo.sx.util.ResultMap;
import com.hhh.demo.sx.util.SessionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author hhh
 * @since 2022-01-04
 */
@Controller
@RequestMapping("/shop")
public class ShopController {
    @Autowired
    private ShopService shopService;


    /**
     * 打开商店主页面
     */
    @RequestMapping("/index")
    public String openPage() {
        return "shop";
    }

    /**
     * 查询所有商店列表
     */
    @ResponseBody
    @RequestMapping("/list")
    public Map<String, Object> getList(@RequestParam("page") int p,
                                       @RequestParam("limit") int limit,
                                       @RequestParam(value = "condition", required = false) String condition) {

        return shopService.findAll(p, limit, condition);

    }


    /**
     * 新增/修改商店
     */
    @ResponseBody
    @RequestMapping("/saveOrUpdate")
    public ResultMap saveOrUpdate(Shop shop) {

        QueryWrapper<Shop> wrapper = new QueryWrapper<>();
        wrapper.eq("name", shop.getName());
        if (shopService.getOne(wrapper) != null&&shop.getId()==null) {
            throw new MyException("用户名已存在");

        }
        boolean f = shopService.saveOrUpdate(shop);
        if (f) {
            return ResultMap.success();
        } else {
            return ResultMap.fail();
        }
    }

    /**
     * 查找商店
     */
    @ResponseBody
    @RequestMapping("/getOne")
    public ResultMap getOne(int id) {
        Shop shop = shopService.getById(id);
        return ResultMap.success(shop);
    }

    /**
     * 删除商店
     */
    @ResponseBody
    @RequestMapping("/delete")
    public ResultMap delete(int id) {
        boolean f = shopService.removeById(id);
        if (f) {
            return ResultMap.success();
        } else {
            return ResultMap.fail();
        }
    }

    /**
     *根据用户Id获取商店
     */
    @ResponseBody
    @RequestMapping("/getByUserID")
    public ResultMap getByUserID() {
        User user= SessionUtil.getCurrentUser();
        QueryWrapper<Shop> wrapper = new QueryWrapper<>();
        wrapper.eq("createby", user.getName());
        return ResultMap.success(shopService.list(wrapper));
    }
}